package com.pyp.kuaishou.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

/**
 * 智能评论生成服务类
 * 调用阿里云DashScope API生成智能评论
 * 
 * @author lauJinyu
 * @date 2025-01-30
 */
@Service
@Slf4j
public class AiCommentService {

    /**
     * 阿里云DashScope API配置
     */
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private static final String API_KEY = "sk-1a73f3cfb73c459f87e739aebbed6b3c";
    private static final String MODEL = "qwen-plus";
    
    private final RestTemplate restTemplate;
    
    public AiCommentService() {
        this.restTemplate = new RestTemplate();
    }

    /**
     * 直接使用输入内容生成智能评论（不使用预定义的评论类型）
     * 该方法直接将输入内容作为完整的AI提示词，适用于materials表中的content字段
     * 
     * @param input 输入内容（作为完整的AI提示词）
     * @return Map 返回结果Map
     */
    public Map<String, Object> generateCommentFromContent(String input) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 参数验证
            if (input == null || input.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "输入内容不能为空");
                return result;
            }

            log.info("开始使用内容生成智能评论，input: {}", input);

            // 2. 构建请求数据（直接使用输入内容作为用户消息，不使用系统提示）
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("model", MODEL);
            
            Map<String, Object> inputData = new HashMap<>();
            List<Map<String, Object>> messages = new ArrayList<>();
            
            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", input);
            messages.add(userMessage);
            
            inputData.put("messages", messages);
            requestData.put("input", inputData);
            
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("result_format", "message");
            requestData.put("parameters", parameters);

            // 3. 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + API_KEY);
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestData, headers);

            // 4. 调用阿里云DashScope API
            ResponseEntity<Map> response = restTemplate.exchange(
                API_URL, 
                HttpMethod.POST, 
                entity, 
                Map.class
            );

            // 5. 处理响应
            if (!response.getStatusCode().is2xxSuccessful()) {
                String errorMsg = "调用阿里云API失败，HTTP状态码：" + response.getStatusCode();
                log.error(errorMsg + ", 响应体: {}", response.getBody());
                result.put("success", false);
                result.put("message", errorMsg);
                return result;
            }

            Map<String, Object> responseData = response.getBody();
            if (responseData == null) {
                log.error("阿里云API响应为空");
                result.put("success", false);
                result.put("message", "API响应为空");
                return result;
            }

            // 6. 验证响应数据结构
            Map<String, Object> output = (Map<String, Object>) responseData.get("output");
            if (output == null) {
                log.error("阿里云API响应格式异常，缺少output字段: {}", responseData);
                result.put("success", false);
                result.put("message", "API响应格式异常");
                return result;
            }
            
            List<Map<String, Object>> choices = (List<Map<String, Object>>) output.get("choices");
            if (choices == null || choices.isEmpty()) {
                log.error("阿里云API响应格式异常，缺少choices字段: {}", responseData);
                result.put("success", false);
                result.put("message", "API响应格式异常");
                return result;
            }
            
            Map<String, Object> firstChoice = choices.get(0);
            Map<String, Object> message = (Map<String, Object>) firstChoice.get("message");
            if (message == null) {
                log.error("阿里云API响应格式异常，缺少message字段: {}", responseData);
                result.put("success", false);
                result.put("message", "API响应格式异常");
                return result;
            }
            
            String generatedComment = (String) message.get("content");
            if (generatedComment == null || generatedComment.trim().isEmpty()) {
                log.error("阿里云API返回的内容为空: {}", responseData);
                result.put("success", false);
                result.put("message", "AI生成的内容为空");
                return result;
            }

            log.info("使用内容生成智能评论成功，input: {}, generated_comment: {}", input, generatedComment);

            // 7. 返回标准化结果
            result.put("success", true);
            result.put("comment", generatedComment);
            result.put("input", input);
            result.put("message", "评论生成成功");
            
            return result;
            
        } catch (HttpClientErrorException e) {
            String errorMsg = "调用阿里云API客户端错误: " + e.getStatusCode() + " - " + e.getResponseBodyAsString();
            log.error(errorMsg, e);
            result.put("success", false);
            result.put("message", errorMsg);
            return result;
            
        } catch (HttpServerErrorException e) {
            String errorMsg = "调用阿里云API服务器错误: " + e.getStatusCode() + " - " + e.getResponseBodyAsString();
            log.error(errorMsg, e);
            result.put("success", false);
            result.put("message", errorMsg);
            return result;
            
        } catch (ResourceAccessException e) {
            String errorMsg = "调用阿里云API网络超时或连接失败: " + e.getMessage();
            log.error(errorMsg, e);
            result.put("success", false);
            result.put("message", errorMsg);
            return result;
            
        } catch (Exception e) {
            String errorMsg = "使用内容生成智能评论失败: " + e.getMessage();
            log.error(errorMsg, e);
            result.put("success", false);
            result.put("message", errorMsg);
            return result;
        }
    }
    
    /**
     * 对AI生成的内容进行字符长度限制处理
     * 如果超过12个字符则截取前12个字符
     * 
     * @param content AI生成的内容
     * @return 处理后的内容
     */
    public String limitContentLength(String content) {
        if (content == null || content.trim().isEmpty()) {
            return content;
        }
        
        String trimmedContent = content.trim();
        if (trimmedContent.length() > 12) {
            String limitedContent = trimmedContent.substring(0, 12);
            log.info("AI生成内容超过12个字符，已截取: 原内容[{}] -> 截取后[{}]", trimmedContent, limitedContent);
            return limitedContent;
        }
        
        return trimmedContent;
    }
}